// pages/orderList/orderList.js
let App = getApp()
import request from '../../utils/index'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 当前口袋
    packageMode: 0,
    // 搜索框聚焦
    inputFocus: false,
    // 搜索框值
    inputValue: '',
    // 当前订单模式
    pageElement: '',
    // 标题
    title: '',
    // 商品分类数组
    category: [],
    // 口袋数组
    buttonArr: [
      {
        index: 0,
        text: '口袋 1',
        selected: true,
      },
    ],
    // 初始商品数组
    orderItem: [],
    // 页面展示数组
    showOrderList: [],
    // 口袋中的商品数组
    selectedList: [],
    // 购物车数组
    shoppingList: [[]],
    // 所选的商品总数
    selectedAll: 0,
    // 总价格
    totalPrice: {
      1: 0,
    },
    // 搜索顶部栏是否显示
    searchNavShow: false,
    // 总价格
    allPrice: 0,
    // 购物车是否展开
    isMaskShow: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      pageElement: options.listby,
    })
    let title
    if (options.listby === 'bike') {
      title = '外卖到家'
    } else if (options.listby === 'home') {
      title = '到店自取'
    } else if (options.listby === 'plane') {
      title = '顺风速递'
    } else {
      return
    }
    this.setData({
      title,
      navHeight: App.globalData.navHeight,
      statusHeight: App.globalData.statusBarHeight,
    })
    request(
      {
        url: 'http://120.78.172.212:9001/api/goods_type',
      },
      (res) => {
        console.log(res)
        let category = this.data.category
        res.data.map((item) => {
          item.State = false
          category.push(item)
          return item
        })
        category[0].State = true
        this.setData({
          category,
        })
      }
    )
    request(
      {
        url: 'http://120.78.172.212:9001/api/goods?limit=100&page=1',
      },
      (res) => {
        let orderItem = [...res.data.rows]
        orderItem.map((x) => {
          x.isStore = false
          x.num = 0
          return x
        })
        this.setData({
          orderItem,
        })
        this.initPackageList()
        this.filterOrderItems()
      }
    )
  },
  // input框显示
  showInput() {
    this.setData({
      inputFocus: true,
    })
  },
  // blur事件
  test2(e) {
    // console.log(e);
    if (!e.detail.value) {
      this.setData({
        inputFocus: false,
      })
    }
  },

  // 分类菜单点击函数
  cateHandler(e) {
    let category = this.data.category
    // console.log(this.data.category);
    let index = category.findIndex((x) => {
      return x.type === e.currentTarget.dataset.catetext
    })
    category.forEach((item) => {
      item.State = false
    })
    category[index].State = true
    this.setData({
      category,
    })
    this.filterOrderItems()
  },

  // 选中商品加加操作
  addSelectedNum(e) {
    let item_id = e.currentTarget.dataset.id
    let selectedList = JSON.parse(JSON.stringify(this.data.selectedList))
    let mode = this.data.packageMode
    let orderItem = selectedList[mode]
    let totalPrice = this.data.totalPrice
    let selectedAll = this.data.selectedAll
    let allPrice = this.data.allPrice
    let shopPackage = this.data.shoppingList[this.data.packageMode]

    // console.log(orderItem);
    let item = orderItem.find((x) => {
      return x.id == item_id
    })
    if (item.num < 99) {
      item.num++
      selectedAll++
      totalPrice[this.data.packageMode + 1] =
        Math.round(
          totalPrice[this.data.packageMode + 1] * 100 + item.price * 100
        ) / 100
      console.log(item.price * 100)
      console.log(allPrice * 100)
      console.log(100 * item.price)
      allPrice = Math.round(allPrice * 100 + 100 * item.price) / 100
    }
    // 对购物车数组的操作
    let isAlive = shopPackage.findIndex((x) => {
      return x.id == item.id
    })
    if (isAlive != -1) {
      shopPackage[isAlive] = { ...item }
    } else {
      shopPackage.push(item)
    }
    this.setData({
      selectedList,
      selectedAll,
      totalPrice,
      allPrice,
    })
    this.filterOrderItems()
  },

  // 选中商品减减操作
  subSelectedNum(e) {
    let item_id = e.currentTarget.dataset.id
    let selectedList = JSON.parse(JSON.stringify(this.data.selectedList))
    let mode = this.data.packageMode
    let orderItem = selectedList[mode]
    let totalPrice = this.data.totalPrice
    let selectedAll = this.data.selectedAll
    let allPrice = this.data.allPrice
    let shopPackage = this.data.shoppingList[this.data.packageMode]
    // console.log(orderItem);
    let item = orderItem.find((x) => {
      return x.id == item_id
    })
    if (item.num > 0) {
      item.num--
      selectedAll--
      totalPrice[this.data.packageMode + 1] =
        Math.round(
          totalPrice[this.data.packageMode + 1] * 100 - item.price * 100
        ) / 100
      allPrice = Math.round(allPrice * 100 - item.price * 100) / 100
    }
    if (item.num == 0) {
      this.data.shoppingList[this.data.packageMode] = shopPackage.filter(
        (x) => {
          return x.id != item_id
        }
      )
    } else {
      let isAlive = shopPackage.findIndex((x) => {
        return x.id == item_id
      })
      shopPackage[isAlive] = { ...item }
    }
    this.setData({
      selectedList,
      selectedAll,
      totalPrice,
      allPrice,
    })
    this.filterOrderItems()
  },
  storeHandler() {},
  // 前往详情页面
  toDetails(e) {
    let item = JSON.stringify(e.currentTarget.dataset.item)
    wx.navigateTo({
      url: '../details/details?item=' + item,
      success: (result) => {},
      fail: () => {},
      complete: () => {},
    })
  },
  //前往支付页面
  toPayment() {
    let selectedList = this.data.selectedList
    selectedList.totalPrice = this.data.totalPrice
    let StringText = JSON.stringify(selectedList)
    // console.log(StringText)
    wx.navigateTo({
      url: '../payment/payment?list=' + StringText,
      success: (result) => {},
      fail: () => {},
      complete: () => {},
    })
  },
  //监听页面滑动
  onPageScroll(e) {
    if (e.scrollTop > 115) {
      this.setData({
        searchNavShow: true,
      })
    } else {
      this.setData({
        searchNavShow: false,
      })
    }
  },
  // 初始化口袋数组
  initPackageList() {
    let orderItem = [...this.data.orderItem]
    let selectedList = [...this.data.selectedList]
    let mode = this.data.packageMode
    selectedList.push([...orderItem])
    this.setData({
      selectedList,
    })
  },
  // 过滤数组
  filterOrderItems() {
    // 定义当前类型id
    let type_id = this.data.category.find((x) => {
      return x.State == true
    }).id
    // console.log(this.data.selectedList)
    // 锁定到当前口袋数组
    let item = this.data.selectedList[this.data.packageMode]
    // console.log(item)
    let showOrderList
    if (type_id == 1) {
      this.setData({
        showOrderList: item,
      })
    } else if (type_id == -2) {
      showOrderList = item.filter((x) => {
        return x.isStore == true
      })
      this.setData({
        showOrderList,
      })
    } else {
      showOrderList = item.filter((x) => {
        return x.type_id == type_id
      })
      this.setData({
        showOrderList,
      })
    }

    // console.log(this.data.showOrderList);
  },
  // 改变口袋
  changePackage(e) {
    let index = e.currentTarget.dataset.index
    let buttonArr = this.data.buttonArr
    buttonArr.map((x) => {
      return (x.selected = false)
    })
    buttonArr[index].selected = true
    this.setData({
      packageMode: index,
      buttonArr,
    })
    this.filterOrderItems()
  },
  // 添加口袋
  addPackage() {
    /* 
      逻辑有问题
    */
    let buttonArr = this.data.buttonArr
    let length = buttonArr.length
    let selectedList = this.data.selectedList
    let orderitem = this.data.orderItem
    let shoppingList = this.data.shoppingList
    let totalPrice = this.data.totalPrice
    let item = {
      index: length,
      text: '口袋 ' + parseInt(length + 1),
      selected: false,
    }
    let textName = parseInt(length + 1)
    totalPrice[textName] = 0
    buttonArr.push(item)
    selectedList.push(orderitem)
    shoppingList.push([])
    this.setData({
      buttonArr,
      selectedList,
      totalPrice,
    })
  },
  // 确认创建订单
  commitToCreateOrder() {
    if (
      this.data.shoppingList.length == 1 &&
      this.data.shoppingList[0].length == 0
    ) {
      return
    }
    // console.log(this.data.shoppingList)
    request(
      {
        url: 'http://120.78.172.212:9001/api/order',
        method: 'post',
        data: {
          remarks: '',
          pockets: this.data.shoppingList,
        },
      },
      function (data) {
        console.log(data)
        if (data.success == true) {
          wx.navigateTo({
            url: '../payment/payment?payment_id=' + data.data,
          })
        }
      }
    )
  },
})
